package com.kelab.dify.service;

import com.kelab.dify.config.DifyConfig;
import com.kelab.dify.exception.DifyException;
import com.kelab.dify.service.base.BaseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 应用服务类
 * 提供应用管理相关功能
 * 
 * @author kelab
 * @version 1.0
 */
public class ApplicationService extends BaseService {
    
    private static final Logger logger = LoggerFactory.getLogger(ApplicationService.class);
    
    private static final String META_ENDPOINT = "meta";
    private static final String FEEDBACK_ENDPOINT = "messages/{message_id}/feedbacks";
    private static final String SUGGESTED_QUESTIONS_ENDPOINT = "messages/{message_id}/suggested";
    
    /**
     * 构造函数
     * 
     * @param httpClient HTTP客户端
     * @param objectMapper JSON映射器
     * @param config 配置信息
     */
    public ApplicationService(OkHttpClient httpClient, ObjectMapper objectMapper, DifyConfig config) {
        super(httpClient, objectMapper, config);
    }
    
    /**
     * 获取应用元信息
     * 
     * @param user 用户标识
     * @return 应用元信息响应
     * @throws DifyException 如果请求失败
     */
    public ApplicationMetaResponse getApplicationMeta(String user) throws DifyException {
        String url = config.getFullUrl(META_ENDPOINT) + "?user=" + user;
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, ApplicationMetaResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get application meta", e);
        }
    }
    
    /**
     * 提交消息反馈
     * 
     * @param messageId 消息ID
     * @param rating 评分（like/dislike）
     * @param content 反馈内容（可选）
     * @param user 用户标识
     * @return 反馈响应
     * @throws DifyException 如果请求失败
     */
    public FeedbackResponse submitFeedback(String messageId, String rating, String content, String user) throws DifyException {
        String url = config.getFullUrl(FEEDBACK_ENDPOINT.replace("{message_id}", messageId));
        
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{");
        jsonBuilder.append("\"rating\":\"").append(rating).append("\",");
        jsonBuilder.append("\"user\":\"").append(user).append("\"");
        
        if (content != null && !content.isEmpty()) {
            jsonBuilder.append(",\"content\":\"").append(content.replace("\"", "\\\"")).append("\"");
        }
        jsonBuilder.append("}");
        
        RequestBody body = RequestBody.create(jsonBuilder.toString(), JSON_MEDIA_TYPE);
        
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", config.getAuthorizationHeader())
                .addHeader("Content-Type", "application/json")
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FeedbackResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to submit feedback", e);
        }
    }
    
    /**
     * 获取建议问题
     * 
     * @param messageId 消息ID
     * @param user 用户标识
     * @return 建议问题响应
     * @throws DifyException 如果请求失败
     */
    public SuggestedQuestionsResponse getSuggestedQuestions(String messageId, String user) throws DifyException {
        String url = config.getFullUrl(SUGGESTED_QUESTIONS_ENDPOINT.replace("{message_id}", messageId)) + "?user=" + user;
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, SuggestedQuestionsResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get suggested questions", e);
        }
    }
    
    /**
     * 获取应用配置
     * 
     * @return 应用配置响应
     * @throws DifyException 如果请求失败
     */
    public ApplicationConfigResponse getApplicationConfig() throws DifyException {
        String url = config.getFullUrl("app-config");
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, ApplicationConfigResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get application config", e);
        }
    }
    
    /**
     * 获取应用统计信息
     * 
     * @param start 开始时间戳（可选）
     * @param end 结束时间戳（可选）
     * @return 统计信息响应
     * @throws DifyException 如果请求失败
     */
    public ApplicationStatsResponse getApplicationStats(Long start, Long end) throws DifyException {
        StringBuilder urlBuilder = new StringBuilder(config.getFullUrl("statistics"));
        
        boolean hasParams = false;
        if (start != null) {
            urlBuilder.append("?start=").append(start);
            hasParams = true;
        }
        if (end != null) {
            urlBuilder.append(hasParams ? "&" : "?").append("end=").append(end);
        }
        
        Request request = new Request.Builder()
                .url(urlBuilder.toString())
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, ApplicationStatsResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get application stats", e);
        }
    }
    
    // 内部响应类定义
    public static class ApplicationMetaResponse {
        private String tool_icons;
        
        // Getter和Setter方法
        public String getToolIcons() {
            return tool_icons;
        }
        
        public void setToolIcons(String tool_icons) {
            this.tool_icons = tool_icons;
        }
    }
    
    public static class FeedbackResponse {
        private boolean success;
        
        // Getter和Setter方法
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
    }
    
    public static class SuggestedQuestionsResponse {
        // 根据实际API响应结构定义字段
    }
    
    public static class ApplicationConfigResponse {
        // 根据实际API响应结构定义字段
    }
    
    public static class ApplicationStatsResponse {
        // 根据实际API响应结构定义字段
    }
}